//
//  TCBGMListViewController.m
//  TXXiaoShiPinDemo
//
//  Created by linkzhzhu on 2017/12/8.
//  Copyright © 2017年 tencent. All rights reserved.
//

#import "TCBGMListViewController.h"
#import "TCBGMHelper.h"
#import "UIView+CustomAutoLayout.h"
#import "TCBGMCell.h"
#import "MBProgressHUD.h"
#import <MediaPlayer/MPMediaPickerController.h>
#import "AVPlayerManager.h"
#import "MHAVAudioManager.h"
#import "MHMusicCatergoryTableViewController.h"
#import "MHMusicCatergory.h"
#import "MHCommonCollectionViewCell.h"
#import "UIScrollView+MHRefresh.h"
#import "MHMusicCatergoryViewModel.h"
#import "MHBGMListViewModel.h"

static const CGFloat JXheightForHeaderInSection = 50;
@interface TCBGMListViewController()<TCBGMHelperListener,TCBGMCellDelegate,MPMediaPickerControllerDelegate,JXCategoryViewDelegate,JXPagingViewDelegate,MHCommonTableListViewDelegate>{
    NSMutableDictionary* _progressList;
    NSTimeInterval lastUIFreshTick;
}
@property(nonatomic,strong) NSDictionary* bgmDict;
//@property(nonatomic,strong) NSArray* bgmKeys;
@property(nonatomic,strong) TCBGMHelper* bgmHelper;
@property(nonatomic,weak) id<TCBGMControllerListener> bgmListener;
@property(nonatomic, strong) MHCommonCollectionViewBoxView *headerBoxView;
@property (nonatomic, strong) JXPagingView *pagingView;
@property (nonatomic, strong) NSArray <MHCommonTableBoxView *> *listViewArray;
@property(nonatomic, strong) MHDataSource *dataSource;
@property(nonatomic, strong) MHDataSource *localDataSource;

@property(nonatomic, strong) MHDataSource *collecitonDataSource;
@property(nonatomic, strong) MHBGMListViewModel *viewModel;
@property(nonatomic, strong) TCBGMCell *currentCell;
//@property(nonatomic, assign) int <#name#>;
@property(nonatomic, assign) int currentRow;
@property(nonatomic, strong) TCBGMElement *currentElement;
@end


@implementation TCBGMListViewController
{
    TCBGMCell *_BGMCell;
    MBProgressHUD *_hub;
    BOOL      _useLocalMusic;
}
@dynamic viewModel;

-(void)setBGMControllerListener:(id<TCBGMControllerListener>) listener{
    _bgmListener = listener;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewDidLoad{
    [super viewDidLoad];
    self.title = @"选择音乐";
    self.currentRow = - 1;
    _progressList = [NSMutableDictionary new];
    UIBarButtonItem *customBackButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    self.navigationItem.leftBarButtonItem = customBackButton;
    self.navigationController.navigationBar.translucent  =  NO;
    MHMusicCatergoryViewModel *viewModel = [[MHMusicCatergoryViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelCommonModelUtilKey:@(true)}];
    MHMusicCatergoryTableViewController *catergoryVc = [[MHMusicCatergoryTableViewController alloc] initWithViewModel:viewModel];
    self.searchController = [self configSearchViewControllerWithResultViewController:catergoryVc];
    [self setUpSubViews];
    [self initData];
    [self loadBGMList];
    self.bgmListener = self.viewModel.delegate;
}

-(void) initData
{
    @weakify(self);
    [[[[MHHTTPService sharedInstance] getSongCategoryList] mh_parsedResults] subscribeNext:^(NSArray *songs) {
        @strongify(self);
        self.catergoryData = songs;
        CGFloat headerHegiht =  (self.catergoryData.count%4 == 0) ? self.catergoryData.count/4*80 : (self.catergoryData.count/4 + 1) *80;
        self.headerBoxView.frame =  CGRectMake(0, 0, MH_SCREEN_WIDTH, headerHegiht + 10);
        self.pagingView.mainTableView.tableHeaderView = self.headerBoxView;
        [self.collecitonDataSource reloadWithItems:songs];
        
    }];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self.pagingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.searchController.searchBar.mas_bottom);
    }];
}




#pragma mark - TestListViewDelegate

- (void)listViewDidScroll:(UIScrollView *)scrollView {
    [self.pagingView listViewDidScroll:scrollView];
}

#pragma mark - JXPagingViewDelegate

- (UIView *)tableHeaderViewInPagingView:(JXPagingView *)pagingView {
    
    return  self.headerBoxView;
}

- (CGFloat)tableHeaderViewHeightInPagingView:(JXPagingView *)pagingView
{
    return  ((self.catergoryData.count%4 == 0) ? self.catergoryData.count/4*80 : (self.catergoryData.count/4 + 1) *80) + 10;
}

- (CGFloat)heightForPinSectionHeaderInPagingView:(JXPagingView *)pagingView {
    return JXheightForHeaderInSection;
}

- (UIView *)viewForPinSectionHeaderInPagingView:(JXPagingView *)pagingView {
    return self.categoryView;
}

- (NSInteger)numberOfListViewsInPagingView:(JXPagingView *)pagingView {
    return  self.listViewArray.count;
}

- (UIView<JXPagingViewListViewDelegate> *)pagingView:(JXPagingView *)pagingView listViewInRow:(NSInteger)row {
    return self.listViewArray[row];
}

- (void)mainTableViewDidScroll:(UIScrollView *)scrollView {
}


-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    []
    [[MHAVAudioManager shareManager].player replaceCurrentItemWithPlayerItem:nil];
    [MHAVAudioManager shareManager].player = nil;
    [[MHAVAudioManager shareManager] pause];
    
}

-(void) setUpSubViews
{
    _categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, JXheightForHeaderInSection)];
    self.categoryView.titles = @[@"热门",@"本地音乐"];
    self.categoryView.backgroundColor = [UIColor whiteColor];
    self.categoryView.delegate = self;
    self.categoryView.titleSelectedColor = MHTextColor333;
    self.categoryView.titleColor = MHColorFromHexString(@"#8E8E93");
    self.categoryView.titleFont = MHRegularFont_15;
    self.categoryView.titleColorGradientEnabled = YES;
    self.categoryView.titleLabelZoomEnabled = YES;
    self.categoryView.titleLabelZoomEnabled = YES;
    _pagingView = [[JXPagingView alloc] initWithDelegate:self];
    [self.view addSubview:self.pagingView];
    self.categoryView.contentScrollView = self.pagingView.listContainerView.collectionView;
    self.categoryView.separatorLineShowEnabled = YES;
    self.categoryView.separatorLineColor = WXGlobalBottomLineColor;
    
    MHDataSource *dataSource = [self createCommonDataSource];
    MHCommonTableBoxView *hot = [[MHCommonTableBoxView alloc] initWithFrame:CGRectZero dataSource:dataSource];
    __weak __typeof(self)weakSelf = self;
    [hot.tableView mh_addFooterRefresh:^(MJRefreshAutoNormalFooter *footer) {
         [weakSelf loadData];
    }];
    hot.delegate = self;
    self.dataSource = dataSource;
    
    
    
    
    MHDataSource *localDataSource = [self createCommonDataSource];
    MHCommonTableBoxView *localMusic = [[MHCommonTableBoxView alloc] initWithFrame:CGRectMake(0, 0, MH_SCREEN_WIDTH, 400) dataSource:localDataSource];
    
    localMusic.delegate = self;
    self.localDataSource = localDataSource;
    _listViewArray = @[hot,localMusic];
}


-(MHDataSource *) createCommonDataSource
{
    NSDictionary *modelCellMap = @{@"TCBGMElement":@"TCBGMCell",};
    MHDataSource *dataSource = [[MHDataSource alloc] initWithModelCellMap:modelCellMap cellConfigBlock:^(TCBGMCell *cell, TCBGMElement *ele, NSIndexPath *indexPath) {
        cell.delegate = self;
        cell.timeLabel.text = ele.timeLength;
        cell.authorLabel.text = ele.artists;
        cell.isLocal = ele.dataFromLocal;
        if ([ele.fullSongUrl isEqualToString:self.currentElement.fullSongUrl] && [MHAVAudioManager shareManager].isPlaying) {
            cell.playBtn.selected = YES;
        }else
        {
            cell.playBtn.selected = NO;
        }
//        cell.playBtn.selected = [ele.fullSongUrl isEqualToString:self.currentElement.fullSongUrl] ?  YES :  [MHAVAudioManager shareManager].isPlaying;
//        cell.playBtn.hidden =  ![ele.fullSongUrl isEqualToString:self.currentElement.fullSongUrl] ;
        if (!ele.dataFromLocal) {
            [cell.musicIcon yy_setImageWithURL:[NSURL URLWithString:ele.fullCoverUrl] placeholder:[UIImage imageNamed:@"img_music_default"]];
            
            if ([ele isCacheInLocal]) {
                [cell setDownloadProgress:1.0];
                cell.progressView.hidden = NO;
            }else{
                cell.progressView.hidden = YES;
                [cell.downLoadBtn setTitle:@"使用" forState:UIControlStateNormal];
            }
        }else
        {
            cell.musicIcon.image = ele.image;
        }
       
        cell.musicLabel.text = ele.title;
    }];
    
    __weak __typeof(dataSource)weakDataSource = dataSource;
    dataSource.didSelectCellBlock = ^(TCBGMElement *item, NSIndexPath *indexPath) {
        
        
        TCBGMCell * cell = [weakDataSource.tableView cellForRowAtIndexPath:indexPath];
        self.currentCell = cell;
//        self.currentRow = indexPath.row;
        self.currentElement = item;
        @weakify(self);
//        [RACObserve([MHAVAudioManager shareManager], isPrepare) subscribeNext:^(NSNumber *num) {
//            @strongify(self);
//            self.currentCell.playBtn.hidden =  ![num boolValue];
//        }];
        [RACObserve([MHAVAudioManager shareManager], isPlaying) subscribeNext:^(NSNumber *num) {
            @strongify(self);
            self.currentCell.playBtn.selected =  [num boolValue];
        }];
        
        MHAVAudioManager *manger = [MHAVAudioManager shareManager];
        NSURL *palyUrl = item.dataFromLocal ? item.musicUrl : [NSURL URLWithString:item.fullSongUrl];
        if ([[manger currentUrl] isEqual:palyUrl]) {
            if (manger.isPlaying) {
                [manger pause];
            }else
            {
                [manger play];
            }
        }else
        {
            [manger musicPlayerWithURL:palyUrl];
        }
        [weakDataSource.tableView reloadData];
    };
    
    
    dataSource.heightForRow = ^CGFloat (id item, NSIndexPath *indexPath) {
        return 80;
    };
    
    return dataSource;
}

-(MHCommonCollectionViewBoxView *)headerBoxView
{
    if (!_headerBoxView) {
        
        CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
        
        layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
        layout.headerHeight = 5;
        layout.footerHeight = 5;
        layout.columnCount = 4;
        layout.minimumColumnSpacing = 5;
        layout.minimumInteritemSpacing = 5;
        NSDictionary *modelCellMap = @{ @"MHMusicCatergory":@"MHCommonCollectionViewCell",  };
        MHDataSource *dataSource = [[MHDataSource alloc] initWithModelCellMap:modelCellMap cellConfigBlock:^(MHCommonCollectionViewCell *cell, MHMusicCatergory *item, NSIndexPath *indexPath) {
            cell.nameLabel.text = item.title;
            [cell.imageView yy_setImageWithURL:[NSURL URLWithString:item.fullIconUrl] placeholder: MHDefaultAvatar(MHDefaultAvatarTypeSmall)];
        }];
        dataSource.collectionViewLayoutSize = ^CGSize(WFDataSourceSection *sectionItem, UICollectionViewLayout *collectionViewLayout, NSIndexPath *indexPath) {
            return CGSizeMake((MH_SCREEN_WIDTH - 5*5) / 4, 70);
        };
        dataSource.collectionSectionInset = ^UIEdgeInsets(WFDataSourceSection *sectionItem, NSInteger section) {
            return UIEdgeInsetsMake(5, 5, 5, 5);
        };
        dataSource.didSelectCellBlock = ^(MHMusicCatergory *item, NSIndexPath *indexPath) {
            MHMusicCatergoryViewModel *viewModel = [[MHMusicCatergoryViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelUtilKey : @(item.autoId),MHViewModelTitleKey:item.title}];
            [self.viewModel.services pushViewModel:viewModel animated:YES];
        };
        _headerBoxView = [[MHCommonCollectionViewBoxView alloc] initWithFrame:CGRectZero layout:layout dataSouce:dataSource];
        self.collecitonDataSource = dataSource;
    }
    return _headerBoxView;
}

- (void)goBack
{
    [_bgmListener onBGMControllerPlay:nil];
    [self.viewModel.services dismissViewModelAnimated:YES completion:nil];
    if (self.searchController) {
        [self.searchController endSearch];
    }
}

- (void)loadBGMList{
    lastUIFreshTick = [[NSDate date] timeIntervalSince1970]*1000;
    _bgmHelper = [TCBGMHelper sharedInstance];
    [_bgmHelper setDelegate:self];
    [self loadData];
    
}

-(void) loadData
{
    MHCommonTableBoxView *hot =    self.listViewArray.firstObject;
    if(hot.pageIndex > 1)
    {
        return;
    }
    [_bgmHelper loadBGMListFormRemoteWithPageNum:hot.pageIndex pageSize:hot.perPage finishBlock:^(NSArray *songs){
        hot.pageIndex ++;
        [hot.tableView.mj_footer endRefreshing];
//        if (songs.count <hot.perPage) {
            [hot.tableView.mj_footer endRefreshingWithNoMoreData];
//        }
        
    } errBlock:^{
        [hot.tableView.mj_footer endRefreshing];
    }];

}


- (void)playerItemDidReachEnd:(NSNotification *)notification {
    
}

- (void)onBGMDownLoad:(TCBGMCell *)cell;
{
    _BGMCell = cell;
    if (cell.isLocal) {
        MHCommonTableBoxView *local =   self.listViewArray.lastObject;
        NSIndexPath *indexPath = [local.tableView indexPathForCell:_BGMCell];
        TCBGMElement* ele =  [_bgmHelper loadLocalMusic][indexPath.row];
        self.localCurrentSong = ele;
        [MBProgressHUD mh_showProgressHUD:@"音乐读取中..."];
        [self saveAssetURLToFile:ele.musicUrl];
    }else
    {
        MHCommonTableBoxView *hot =   self.listViewArray.firstObject;
        NSIndexPath *indexPath = [hot.tableView indexPathForCell:_BGMCell];
        TCBGMElement* ele = [self.bgmDict allValues][indexPath.row]; //_bgmDict[_bgmKeys[indexPath.row]];
        
        [AXAppDelegate sharedDelegate].currentSong = ele;
        NSString *cacheName = [NSString stringWithFormat:@"%@.%@",[ele title],[[ele fullSongUrl] pathExtension]];
        NSString *cachePath = [NSHomeDirectory() stringByAppendingPathComponent: [NSString stringWithFormat:@"Documents/bgm/%@", cacheName]];
        if([[NSFileManager defaultManager] fileExistsAtPath:cachePath]){
            [self goBack];
            [_bgmListener onBGMControllerPlay:cachePath];
        }
        else [_bgmHelper downloadBGM: [self.bgmDict allValues][indexPath.row]];
    }
    
}


-(void) onBGMListLoad:(NSDictionary*)dict{
    BOOL findKeyBGM = YES;
    if(dict){
        _bgmDict = dict;
        for (NSString* url in [self.bgmDict allKeys]) {
            TCBGMElement* ele = [_bgmDict objectForKey:url];
            if([[ele isValid] boolValue]){
                [_progressList setObject :[NSNumber numberWithFloat:1.f] forKey:url];
            }
            findKeyBGM = YES;
        }
    }
    __weak __typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.dataSource reloadWithItems:[weakSelf.bgmDict allValues]];
        [weakSelf.localDataSource reloadWithItems:[weakSelf.bgmHelper loadLocalMusic]];
    });
}

-(void) onBGMDownloading:(TCBGMElement*)current percent:(float)percent{
    dispatch_async(dispatch_get_main_queue(), ^{
        [_BGMCell setDownloadProgress:percent];
    });
}

-(void) onBGMDownloadDone:(TCBGMElement*)element{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if([element isCacheInLocal] || element.isValid){
            BGMLog(@"Download \"%@\" success!", [element title]);
            [_progressList setObject :[NSNumber numberWithFloat:1.f] forKey:[element fullSongUrl]];
            [self goBack];
            NSString *cacheName = [NSString stringWithFormat:@"%@.%@",[element title],[[element fullSongUrl] pathExtension]];
            NSString *cachePath = [NSHomeDirectory() stringByAppendingPathComponent: [NSString stringWithFormat:@"Documents/bgm/%@", cacheName]];
            [_bgmListener onBGMControllerPlay: cachePath];
        }
        else BGMLog(@"Download \"%@\" failed!", [element title]);
    });
    
}


//点击取消时回调
- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    [self goBack];
}

// 将AssetURL(音乐)导出到app的文件夹并播放
- (void)saveAssetURLToFile:(NSURL *)assetURL {
    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
    
    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:songAsset presetName:AVAssetExportPresetAppleM4A];
    NSLog (@"created exporter. supportedFileTypes: %@", exporter.supportedFileTypes);
    exporter.outputFileType = @"com.apple.m4a-audio";
    
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *exportFile = [docDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.m4a",self.localCurrentSong.title]];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:exportFile]) {
        [[NSFileManager defaultManager] removeItemAtPath:exportFile error:nil];
    }
    exporter.outputURL = [NSURL fileURLWithPath:exportFile];
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        int exportStatus = exporter.status;
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD mh_hideHUD];
        });
        
        switch (exportStatus) {
            case AVAssetExportSessionStatusFailed: {
                NSLog (@"AVAssetExportSessionStatusFailed: %@", exporter.error);
                break;
            }
            case AVAssetExportSessionStatusCompleted: {
                NSLog(@"AVAssetExportSessionStatusCompleted: %@", exporter.outputURL);
                
                // 播放背景音乐
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                    [MBProgressHUD mh_hideHUD];
                    [self goBack];
                    [_bgmListener onBGMControllerPlay:exportFile];
                });
                break;
            }
            case AVAssetExportSessionStatusUnknown: { NSLog (@"AVAssetExportSessionStatusUnknown"); break;}
            case AVAssetExportSessionStatusExporting: { NSLog (@"AVAssetExportSessionStatusExporting"); break;}
            case AVAssetExportSessionStatusCancelled: { NSLog (@"AVAssetExportSessionStatusCancelled"); break;}
            case AVAssetExportSessionStatusWaiting: { NSLog (@"AVAssetExportSessionStatusWaiting"); break;}
            default: { NSLog (@"didn't get export status"); break;}
        }
    }];
}
@end
